import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yinsh
 * Date: 2025-02-21
 * Time: 14:27
 */
public class Test {

    public void qSort(int[] array) {
        qSortFunc(array, 0, array.length - 1);
    }

    private void qSortFunc(int[] array, int left, int right) {
        Stack<Integer> stack = new Stack<>();
        int pivot = partition(array, left, right);
        if (pivot+1 < right) {
            stack.push(pivot+1);
            stack.push(right);
        }
        if (pivot-1 > left) {
            stack.push(left);
            stack.push(pivot-1);
        }
        while (!stack.isEmpty()) {
            right = stack.pop();
            left = stack.pop();
            pivot = partition(array, left, right);
            if (pivot+1 < right) {
                stack.push(pivot+1);
                stack.push(right);
            }
            if (pivot-1 > left) {
                stack.push(left);
                stack.push(pivot-1);
            }
        }
    }

    private int partition(int[] array, int left, int right) {
        int key = array[left];
        while (left < right) {
            while (left<right && array[right] >= key) {
                right--;
            }
            array[left] = array[right];
            while (left<right && array[left] <= key) {
                left++;
            }
            array[right] = array[left];
        }
        array[left] = key;
        return left;
    }

    private void swap (int[] array,int x,int y) {
        int tamp = array[x];
        array[x] = array[y];
        array[y] = tamp;
    }
}
